package com.wan.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.wan.config.StaticImageConfig;
import com.wan.entity.GameUser;
import com.wan.service.GameUserService;
import entity.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import utils.TimeUtils;
import utils.UUIDUtils;

import java.io.File;
import java.io.IOException;

/**
 * @author xzx
 * @date 2021/4/17 13:54
 */
@RestController
@RequestMapping("/bs/game")
public class GameUploadController {

    private static final String SEPARATOR = "/";
    private static final long FILE_SIZE = 1024*1024;
    @Autowired
    private StaticImageConfig staticImageConfig;
    @Autowired
    private GameUserService gameUserService;
    @Value("${map.url}")
    private String url;


    @RequestMapping("/file/upload")
    public ResultBean fileUolad(MultipartFile file,Integer userId){
        if (file == null) {
            return new ResultBean(500,"图片不能为空");
        }
        if (file.getSize() == 0 ){
            return new ResultBean(500,"图片不能为空");
        }
        if (file.getSize() > FILE_SIZE){
            return new ResultBean(500,"图片大小不能超过1M");
        }
        String uuid = UUIDUtils.getUUID();
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名{}==>"+file.getOriginalFilename());
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String today = TimeUtils.GetNowDate("yyyy-MM-dd");
        String path = staticImageConfig.getUploadPath();

        //存储文件到磁盘
        StringBuilder dictPath = new StringBuilder();
        dictPath.append(path).append(today).append(SEPARATOR).append(uuid).append(suffix);

        File dictFile = new File(dictPath.toString());
        if(!dictFile.getParentFile().exists()) {
            dictFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dictFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean(500,"文件上传失败");
        }
        JSONObject jsonObject = new JSONObject();
        String src = url+today+SEPARATOR+uuid+suffix;
        String src1 = src.substring(21);
        jsonObject.put("src",src.substring(21));
        if(userId != 0){
            GameUser user = gameUserService.getById(userId);
            user.setFaceImg(src1);
            gameUserService.updateById(user);
        }
        return new ResultBean(0,"文件上传成功",jsonObject);
    }
}
